<template>
  <!-- 放置一个弹层 用来编辑新增节点 -->
  <el-dialog title="添加权限点" :visible.sync="showDialog" @close="btnCancel">
    <!-- 表单 -->
    <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="权限名称" prop="name">
        <el-input v-model="formData.name" style="width: 90%" />
      </el-form-item>
      <el-form-item label="权限标识" prop="code">
        <el-input v-model="formData.code" style="width: 90%" />
      </el-form-item>
      <el-form-item label="权限描述">
        <el-input v-model="formData.description" style="width: 90%" />
      </el-form-item>
      <el-form-item label="开启">
        <el-switch v-model="formData.enVisible" active-value="1" inactive-value="0" />
      </el-form-item>
    </el-form>
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" type="primary" @click="btnOK">确定</el-button>
        <el-button size="small" @click="btnCancel">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getPermissionDetail, addPermission, updatePermission } from '@/api/permission'
export default {
  data() {
    return {
      showDialog: false,
      formData: {
        name: '',
        code: '',
        description: '',
        enVisible: '0',
        type: '', // 1代表模块，2代表按钮，3代表api
        pid: '', // 父id
        id: ''
      },
      rules: {
        // 权限名称和权限标识的唯一性验证
        name: [{ required: true, message: '权限名称不能为空', trigger: 'blur' }],
        code: [{ required: true, message: '权限标识不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 弹层的打开
    async open(obj) {
      if (obj.id) {
        // 查询出该id对应的数据
        this.formData = await getPermissionDetail(obj.id)
      } else {
        this.formData.pid = obj.pid
        this.formData.type = obj.type
      }
      this.showDialog = true
    },
    // 弹层的关闭
    btnCancel() {
      this.showDialog = false
      // 重置表单
      this.$refs.perForm.resetFields()
      // 将数据置空
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = ''
      })
    },
    // 提交添加或者修改
    btnOK() {
      this.$refs.perForm.validate(async isOk => {
        if (!isOk) return false
        if (this.formData.id) {
          // 编辑
          await updatePermission(this.formData)
          this.$message.success('编辑成功')
        } else {
          // 添加
          await addPermission(this.formData)
          this.$message.success('添加成功')
        }
        this.showDialog = false
        this.$emit('get-permission')
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
